using Ebusiness_OrderService.Data;
using NLog.Web;
using Serilog;
using Serilog.Events;
using Serilog.Filters;
using Serilog.Formatting.Compact;
using Serilog.Sinks.RabbitMQ;
using SkyApm.AspNetCore.Diagnostics;
using Volo.Abp.Data;
using Ebusiness_Framework.ConfigCenter;
using Ebusiness_Framework.LogCenter;
using Ebusiness_Framework.SkyAPMConfig;
using Ebusiness_Framework.DistributedTransaction;
using Ebusiness_Framework.ResourcesMonitoring;
using Ebusiness_Framework.Consul;
using Ebusiness_Framework.ConfigLoad;
using Ebusiness_OrderService.Services;

namespace Ebusiness_OrderService;

public class Program
{
    public async static Task<int> Main(string[] args)
    {
        var loggerConfiguration = new LoggerConfiguration()
#if DEBUG
            .MinimumLevel.Debug()
#else
            .MinimumLevel.Information()
#endif
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .MinimumLevel.Override("Microsoft.EntityFrameworkCore", LogEventLevel.Warning)
            .Enrich.FromLogContext()
            .WriteTo.Async(c => c.File("Logs/logs.txt"))
            .WriteTo.Async(c => c.Console());
        #region 日志中心
        //.WriteTo.Async(a => a.Logger(lc => lc        //数据写入到rabbitmq
        //    .Filter.ByIncludingOnly(Matching.FromSource("Ebusiness_OrderService")) // 命名空间前缀匹配
        //    .WriteTo.RabbitMQ((clientCfg, sinkCfg) =>    //数据写入到 RabbitMQ   ,需要手动创建交换机队列
        //    {
        //        //clientCfg.Hostnames.Add("20.255.99.182");
        //        clientCfg.Hostnames.Add("192.168.211.129");
        //        clientCfg.Port = 5672;
        //        clientCfg.Username = "admin";
        //        clientCfg.Password = "admin123";
        //        clientCfg.Exchange = "Ebusiness_OrderService_logs";
        //        clientCfg.ExchangeType = "direct";
        //        clientCfg.RoutingKey = "Ebusiness_OrderService";
        //        clientCfg.DeliveryMode = RabbitMQDeliveryMode.Durable;
        //        clientCfg.VHost = "/";

        //        sinkCfg.TextFormatter = new CompactJsonFormatter(); // 紧凑 JSON，方便 Logstash
        //    }))
        //);
        // 仅命名空间以 Ebusiness_UserService 开头的日志写入 Logstash
        // .WriteTo.Logger(lc => lc
        //    .Filter.ByIncludingOnly(Matching.FromSource("Ebusiness_UserService"))
        //    .WriteTo.TCPSink("tcp://20.255.99.182:9900")
        //);
        #endregion

        //if (IsMigrateDatabase(args))
        //{
        //    loggerConfiguration.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning);
        //    loggerConfiguration.MinimumLevel.Override("Microsoft", LogEventLevel.Warning);
        //}

        Log.Logger = loggerConfiguration.CreateLogger();

        try
        {
            var builder = WebApplication.CreateBuilder(args);
            builder.Host.AddAppSettingsSecretsJson()
                .UseAutofac();
            //.UseSerilog();

            //if (IsMigrateDatabase(args))
            //{
            //    builder.Services.AddDataMigrationEnvironment();
            //}

            #region 加载配置文件
            {
                builder.UseConfigLoad();
            }
            #endregion

            #region 注册中心
            {
                //builder.Services.AddRegisterCenter(builder.Configuration);
            }
            #endregion

            #region 加载nacos配置  配置中心 nacos //加载nacos配置
            {
                //builder.UseConfigCenter();
            }
            #endregion

            #region 集成NLog  日志中心 ELK
            {
                //builder.UseLogCenter();
            }
            #endregion

            #region 配置链路监控
            {
                //配置链路监控
                //builder.Services.UseSkyAPM();
            }
            #endregion

            #region 微服务-分布式事务servicecomb-pack
            {
                //builder.Services.UseDistributedTransaction(builder.Configuration);
            }
            #endregion

            #region 集成使用资源监控
            {
                //builder.Services.AddResourcesMoniter(builder.Configuration);
            }
            #endregion

            #region 集成SignalR服务
            {
                builder.Services.AddSignalR();
            }
            #endregion

            await builder.AddApplicationAsync<Ebusiness_OrderServiceModule>();

            var app = builder.Build();
            await app.InitializeApplicationAsync();


            #region 集成中间件 集成SignalR服务
            {
                app.MapHub<ChatRoomHub>("/maphub/singlr").RequireCors("AllowVueClient");
            }
            #endregion


            Log.Information("Starting Ebusiness_OrderService.");
            await app.RunAsync();
            return 0;
        }
        catch (Exception ex)
        {
            if (ex is HostAbortedException)
            {
                throw;
            }

            Log.Fatal(ex, "Ebusiness_OrderService terminated unexpectedly!");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }

    private static bool IsMigrateDatabase(string[] args)
    {
        return args.Any(x => x.Contains("--migrate-database", StringComparison.OrdinalIgnoreCase));
    }
}
